<?php
// +----------------------------------------------------------------------
// | Niucloud-admin 企业快速开发的多应用管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.niucloud.com
// +----------------------------------------------------------------------
// | niucloud团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: Niucloud Team
// +----------------------------------------------------------------------

namespace app\api\service\order;

use app\core\exception\CommonException;
use app\dict\delivery\DeliveryDict;
use app\dict\order\OrderDeliveryDict;
use app\dict\order\OrderDict;
use app\dict\order\OrderLogDict;
use app\model\delivery\Store;
use app\api\model\order\Order;
use app\api\model\order\OrderDelivery;
use app\service\core\order\CoreOrderCloseService;
use app\service\core\order\CoreOrderCreateService;
use app\service\core\order\CoreOrderFinishService;
use app\service\core\order\CoreOrderRefuseService;
use app\service\core\order\CoreOrderReturnService;
use app\service\core\order\CoreOrderService;
use app\model\pay\Pay;
use app\core\base\BaseApiService;

/**
 *  订单服务层
 */
class OrderService extends BaseApiService
{
    public function __construct()
    {
        parent::__construct();
        $this->model = new Order();
    }


    /**
     * 订单创建
     * @param array $data
     * @return array
     */
    public function create(array $data)
    {
        $data['member_id'] = $this->member_id;
        $data['order_from'] = $this->channel;
        $data['main_type'] = OrderLogDict::MEMBER;
        $data['main_id'] = $this->member_id;
        return (new CoreOrderCreateService())->create($data);
    }


    /**
     * 分页列表
     * @param array $where
     * @return array
     */
    public function getPage(array $where)
    {
        $field = 'order_id,order_no,status';
        $order = 'create_time desc';
        $search_model = $this->model
            ->where([ [ 'member_id', '=', $this->member_id ] ])
            ->withSearch([ 'order_no', 'status','status_group' ], $where)
            ->field($field)
            ->with(
                [
                    'order_goods' => function($query) {
                        $query->field(' order_id,goods_id, sku_id, goods_name, sku_name, goods_image , price, num, goods_money')->append([ 'goods_image_thumb_small' ]);
                        $query->with([ 'card' => function($query) {
                            $query->field('id,sub_title,tags,rarity,ean');
                        }]);
                    }
                ]
            )->order($order)->append([ 'status_name']);

        $list = $this->pageQuery($search_model);

        return $list;
    }

    /**
     * 详情
     * @param int $order_id
     * @return array
     */
    public function getDetail(int $order_id)
    {
        $field = 'order_id,order_no,status,goods_money,consult_money,create_time,is_consult,shop_remark,unboxing_video';
        $info = $this->model->where([ [ 'order_id', '=', $order_id ], [ 'member_id', '=', $this->member_id ] ])->field($field)
            ->with(
                [
                    'order_goods' => function($query) {
                        $query->field('order_id, goods_id, sku_id, goods_name, sku_name, goods_image, price, num, goods_money')->append([ 'goods_image_thumb_small' ]);
                        $query->with([ 'card' => function($query) {
                            $query->field('id,sub_title,tags,rarity,ean');
                        }]);
                    }
                ]
            )->append([  'status_name' ])->findOrEmpty()->toArray();

        return $info;
    }





    /**
     * 同意协商
     * @param $order
     * @return void
     */
    public function agree($order_id)
    {
        $where = array(
            ['order_id', '=', $order_id],
            ['status','=',OrderDict::WAIT_CONSULT]
        );
        $order = $this->model->with('order_goods')->where($where)->findOrEmpty()->toArray();

        if (empty($order)) throw new CommonException('订单不存在或者非待协商单');//订单不存在
        $afterData = [
            'main_type' => OrderLogDict::MEMBER,
            'order_id' => $order_id,
            'main_id' => $this->member_id
        ];
        ( new CoreOrderFinishService() )->finish($order,$afterData);
        return 'SUCCESS';
    }

    /**
     * 拒绝协商
     * @param $order
     * @return void
     */
    public function refuse($order_id)
    {
        $where = array(
            ['order_id', '=', $order_id],
            ['status','=',OrderDict::WAIT_CONSULT]
        );
        $order = $this->model->with('order_goods')->where($where)->findOrEmpty()->toArray();

        if (empty($order)) throw new CommonException('订单不存在或者非待协商单');//订单不存在
        $afterData = [
            'main_type' => OrderLogDict::MEMBER,
            'order_id' => $order_id,
            'main_id' => $this->member_id
        ];
        (new CoreOrderRefuseService())->refuse($order,$afterData);
        return 'SUCCESS';
    }

    /**
     * 申请寄回
     * @param $order
     * @return void
     */
    public function apply($order_id,$data)
    {
        $where = array(
            ['order_id', '=', $order_id],
            ['status','=',OrderDict::WAIT_RETURN]
        );
        $order = $this->model->with('order_goods')->where($where)->findOrEmpty()->toArray();

        if (empty($order)) throw new CommonException('订单不存在或者非待寄回单');//订单不存在
        $afterData = [
            'main_type' => OrderLogDict::MEMBER,
            'order_id' => $order_id,
            'main_id' => $this->member_id
        ];
        $data['member_id'] = $this->member_id;
        (new CoreOrderReturnService())->return($order,$afterData,$data);
        return 'SUCCESS';
    }

    /**
     * 物流信息
     * @param $id
     */
    public function getDeliveryPackage($data)
    {
        $field = 'id, order_id, name, delivery_type, sub_delivery_type, express_company_id, express_number, local_deliver_id, status, create_time';
        $info = ( new OrderDelivery() )->where([ [ 'id', '=', $data[ 'id' ] ] ])->with([
            'company' => function($query) {
                $query->field('company_id, company_name, express_no');
            },
            'order_goods' => function($query) {
                $query->field('goods_name, sku_name, goods_image, delivery_id, num, price')->append([ 'goods_image_thumb_small' ]);
            }
        ])->field($field)->findOrEmpty()->toArray();

        if (!empty($info) && $info['delivery_type'] == OrderDeliveryDict::EXPRESS && $info['sub_delivery_type'] != OrderDeliveryDict::NONE_EXPRESS) {
            $info['mobile'] = $data['mobile'];
            $info = (new CoreOrderService())->deliverySearch($info);
            return $info;
        }
        return $info;
    }
}
